package controllers;

import java.util.HashMap;
import java.util.Map;

import models.Usuario;
import play.mvc.Controller;
import play.mvc.Router;
import util.AuthUtil;

public class OAuth extends Controller {
	public static void start() throws Exception {
		authenticate("/oauth/index");
	}

	public static void index() {
		renderText("Hello, Usuario!");
	}

	public static void authenticate(String callback) throws Exception {
		// 1: get the request token
		Map<String, Object> args = new HashMap<String, Object>();
		args.put("callback", callback);
		String callbackURL = Router.getFullUrl(
				request.controller + ".callback", args);
		AuthUtil.getConnector()
				.authenticate(AuthUtil.getUsuario(), callbackURL);
		AuthUtil.getUsuario().update();
	}

	public static void callback(String callback, String oauth_token,
			String oauth_verifier) throws Exception {
		// 2: get the access token
		Usuario usuario = AuthUtil.getUsuario();

		AuthUtil.getConnector().retrieveAccessToken(usuario, oauth_verifier);

		usuario.update();
		redirect(callback);
	}
}
